<template>
    <el-upload class="avatar-uploader" action="http://localhost:3001/upload/common/" :headers="headers"
        :before-upload="beforeAvatarUpload" :on-success="handleUploadSuccess" :on-error="handleUploadError"
        :show-file-list="false" :data="data" accept="image/*">
        <img v-if="avatar" :src="avatar" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
export default {
    model: {
        prop: 'avatar',
        event: 'change',
    },
    props: {
        avatar: {
            type: String,
            default: '',
        },
        data:{
            type:Object,
            default:()=>{
                return{
                    type:'common'
                }
            },
        }
    },
    data() {
        return {
            headers: { Authorization: `Bearer ${sessionStorage.access_token}` }
        }
    },
    methods: {
        //上传前的检查
        beforeAvatarUpload(file) {
            let reg = /^image\/(jpeg||png)$/;
            const isImage = reg.test(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isImage) {
                this.$message.error('上传头像图片只能是 JPG或者是PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isImage && isLt2M;
        },
        //上传成功
        handleUploadSuccess(res, file) {
            let { status, msg, src } = res;
            if (status) {
                //预览图像
                this.$emit('change',src);
                this.$message.success(msg);
            }
        },
        //上传失败
        handleUploadError(err, file, fileList) {
            let { status, message } = err;
            switch (status) {
                case 400:
                    let { msg, status } = JSON.parse(err.message);
                    this.$message.error(msg);
                    break;
                case 401:
                    let { code } = JSON.parse(message);
                    this.$message.error(`错误代码：401${code},请重新登录账户！`)
                    break;
            }
        },
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>